import React, {useEffect, useState} from 'react';
import ProForm, {ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import {Modal, message, TreeSelect, Form, Upload, Image, Button } from 'antd';
import {addContent, editContent, getCategoryList, infoContent} from '@/services/cms';
import Editor from '@/components/Editor';
import {UploadOutlined, DeleteOutlined, EyeOutlined} from '@ant-design/icons';
import styles from "../index.less";

const Edit = (props) => {
  const {isModalVisible, isShowModal, actionRef, editId} = props;

  const [formLayout] = useState('horizontal');
  const [cateData, setCateData] = useState([])
  const [visible, setVisible] = useState(false); // 预览图片
  const [previewImage, setPreviewImage] = useState(''); // 预览图片地址
  const [imageData, setImageData] = useState([]); // 图片数组
  const [contentData, setContentData] = useState(undefined); // 富文本数据

  // 定义form的实例
  const [formObj] = ProForm.useForm()

  useEffect( () => {
    getCateList()
  }, [])

  const getCateList = () => {
    getCategoryList().then((res) => {
      setCateData(res.data.list)
    })
  }

  const title = editId === null ? '添加内容' : '编辑内容';

  const formItemLayout =
    formLayout === 'horizontal'
      ? {
        labelCol: {span: 4},
        wrapperCol: {span: 20},
      }
      : null;

  const getData = async () => {
    const res = await infoContent({
      content_id: editId,
    })
    res.data.category_pid = res.data.category_pid === 0 ? null : res.data.category_pid
    setImageData([...res.data.imgs])
    setContentData(res.data.content)
    return res.data
  };

  /**
   * 提交按钮
   * @param values
   * @returns {Promise<void>}
   */
  const handleSubmit = async values => {
    const data = values
    // 添加图片
    data.imgs = imageData

    let res = {}
    if (editId === null) {
      res = await addContent(data)
    } else {
      data.content_id = editId
      res = await editContent(data)
    }

    if (res.code === 200) {
      message.success(res.msg)
      actionRef.current.reload()
      isShowModal(false)
    }
  }

  // 递归修改data属性值，配合treeSelect规范数据
  const handleCateData = (data) => {
      let item = [];
      data.map((list, i) => {
        let newData = {};
        newData.value = list.category_id;
        newData.title = list.category_name;
        newData.children = list.children ? handleCateData(list.children) : []; // 如果还有子集，就再次调用自己
        item.push(newData);
      });
      return item;
  };

  const setDetails = content => formObj.setFieldsValue({'content': content})

  /**
   * 作者：糜家智
   * 时间：2022/04/21 14:51:43
   * 功能：移除图片
   */
  function onRemove(index) {
    imageData.splice(index, 1)
    setImageData([...imageData])
  }

  /**
   * 作者：糜家智
   * 时间：2022/04/20 15:45:23
   * 功能：上传图片配置
   */
  const uploadProps = {
    label: '图片',
    name: 'file',
    showUploadList: false,
    action: '/admin/cms.Category/upload',
    accept: '.jpg,.png,.jpeg',
    data: {
      type: 'image',
    },
    headers: {
      AdminToken: localStorage.getItem('access_token') || '',
    },
    beforeUpload(file) {
      if (file.size > 102400 * 5) {
        message.warning('图片不可大于500k~');
        return false;
      }

      if (imageData.length >= 6) {
        message.warning('最多6张图片~');
        return false;
      }

      // message.loading({
      //   content: '图片正在上传中~',
      //   key: 'uploadImg'
      // })
    },
    onChange(info) {
      if (info.file.status === 'done') {
        let res = info.file.response;
        if (res.code == 200) {
          res.data.status = 'done'
          imageData.push(res.data)
          setImageData([...imageData])
          // message.destroy('uploadImg')
          message.success('图片上传成功~')
        } else {
          message.error(res.msg);
        }
      } else if (info.file.status === 'error') {
        message.error('头像上传失败！');
      }
    },
  };

  return (
    <Modal
      title={title}
      visible={isModalVisible}
      onCancel={() => isShowModal(false)}
      footer={null}
      destroyOnClose={true}
      width={750}
    >
      <ProForm
        form={formObj}
        onFinish={values => handleSubmit(values)}
        request={editId == null ? () => {
          return {sort: 50};
        } : () => getData()}
        {...formItemLayout}
        layout={formLayout}
      >
        <ProForm.Item
          label="分类父级"
          name="category_id"
        >
          {/*<Cascader options={cateData} fieldNames={{label: 'category_name', value: 'category_id'}} placeholder="Please select" />*/}
          <TreeSelect
            style={{width: '100%'}}
            dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
            treeData={handleCateData(cateData)}
            placeholder="一级父级"
            treeDefaultExpandAll
            onChange={() => {
            }}
            allowClear={true}
          />
        </ProForm.Item>

        <ProFormText
          name="name"
          label="名称"
          placeholder="请输入名称"
          rules={[
            {required: true, message: '名称不能为空'}
          ]}
        />
        <ProFormText
          name="title"
          label="标题"
          placeholder="请输入标题"
        />
        <ProFormText
          name="keywords"
          label="关键词"
          placeholder="请输入关键词"
        />
        <ProFormTextArea
          name="description"
          label="描述"
          placeholder="请输入描述"
        />
        <ProFormText
          name="url"
          label="链接"
          placeholder="url"
        />

        <Form.Item label="图片">

          <Upload {...uploadProps} >
            <Button icon={<UploadOutlined/>}>点击上传</Button>
            <span className={styles.prompt}>每张图片大小不超过 500 KB，jpg、png格式</span>
          </Upload>

          <div className={styles.preCon}>

            {imageData.map((item, index) => {
              return (
                <div className={styles.preImg} key={index}>
                  <img src={item.url}/>
                  {/* 自定义遮罩 */}
                  <div className={styles.preMask}>
                    <EyeOutlined onClick={() => {
                      setVisible(true);
                      setPreviewImage(item.url)
                    }} className={styles.preIcon}/>
                    <DeleteOutlined onClick={() => onRemove(index)} className={styles.preIcon}/>
                  </div>
                </div>
              )
            })}

          </div>

        </Form.Item>

        <ProFormText
          name="sort"
          label="排序"
        />
        <ProForm.Item
          name="content"
          label="详情"
          rules={[
            {required: true, message: '请输入详情'}
          ]}
        >
          <Editor
            setDetails={setDetails}
            content={contentData}
           />
        </ProForm.Item>

        <Image
          width={0}
          style={{display: 'none'}}
          preview={{
            visible,
            src: previewImage,
            onVisibleChange: (value) => {
              setVisible(value);
            },
          }}
        />

      </ProForm>
    </Modal>
  );
};

export default Edit;
